package com.lookwider.web;

import com.lookwider.beans.JobCategory;
import com.lookwider.beans.Review;
import com.lookwider.beans.User;
import com.lookwider.services.JobsService;
import com.lookwider.services.ReviewService;
import com.lookwider.services.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.AbstractMap;
import java.util.List;
import java.util.Map;

import static com.google.common.collect.Lists.newArrayList;

@Controller
public class NewsController {

    @Autowired
    private JobsService jobsService;
    @Autowired
    private UserService userService;
    @Autowired
    private ReviewService reviewService;

    @RequestMapping( value="/index" )
    public String showMainPage( Model model ) {

        List<JobCategory> jobCategories = jobsService.findAllMainCategories();
        model.addAttribute( "jobCategories", jobCategories );

        return "news";
    }

    @RequestMapping( value = "/reviews/top/users", method = { RequestMethod.POST, RequestMethod.GET } )
    public @ResponseBody List<Map.Entry<User, Review>> getTopUserReviewsJSON(@RequestParam( value = "job") String job, @RequestParam( value = "karma", required = false) String karma ) {

        List<Map.Entry<User, Review>> result = newArrayList();

        try {
            Long jobId = Long.parseLong(job);
            JobCategory category = jobsService.getBy( jobId );

            Long maxKarma = (long) 0;
            if ( !StringUtils.isBlank( karma ) ) {
                maxKarma = Long.parseLong( karma );
            }
            List<User> users = userService.findBatchMaxKarma( category, maxKarma );
            for ( User user : users ) {
                Review review = reviewService.findTopFor( user );
                result.add(new AbstractMap.SimpleEntry<User, Review> (user, review) );
            }
        } catch ( NumberFormatException e ) {
            e.printStackTrace();
        }

        return result;
    }
}
